package com.gitee.qdbp.base.i18n;

import java.util.Locale;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.NoSuchMessageException;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import com.gitee.qdbp.base.utils.I18nTools;
import com.gitee.qdbp.tools.utils.NamingTools;
import com.gitee.qdbp.tools.utils.StringTools;

/**
 * 结果返回码的国际化处理类
 *
 * @author zhaohuihua
 * @version 181107
 */
public class ResultCodeI18nResolver implements IResultCodeI18nResolver {

    private static Logger log = LoggerFactory.getLogger(ResultCodeI18nResolver.class);

    /** 结果返回码资源文件前缀 **/
    private String resultCodePrefix;

    /** {@inheritDoc} **/
    @Override
    public String getResultCodeMessage(String resultCode) {
        Locale locale = I18nTools.getLocale();
        WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();

        String key = generateResultCodeKey(resultCode);
        try {
            String message = context.getMessage(key, null, locale);
            if (key.equals(message)) { // useCodeAsDefaultMessage
                return getDefaultMessage(resultCode, locale);
            } else {
                return message;
            }
        } catch (NoSuchMessageException e) { // 未配置资源文件
            return getDefaultMessage(resultCode, locale);
        }
    }

    private static Pattern CLEAR = Pattern.compile("[^a-zA-Z]+");

    private String getDefaultMessage(String resultCode, Locale locale) {
        if ("zh".equals(locale.getLanguage())) {
            log.trace("No such message: {}, return null then using original message.", resultCode);
            return null;
        } else {
            // 非中文, 返回resultCode转换的默认消息
            String message = calcDefaultMessage(resultCode);
            log.trace("No such message: {}, return converted message: {}", resultCode, message);
            return message;
        }
    }

    /** 未找到资源文件时, 以resultCode转为小写替换掉下划线再首字母大写作为消息返回 */
    private String calcDefaultMessage(String resultCode) {
        String message = resultCode.toLowerCase() + ".";
        message = CLEAR.matcher(message).replaceAll(" ");
        message = NamingTools.capitalize(message);
        return message;
    }

    /** 生成结果返回码资源文件KEY **/
    protected String generateResultCodeKey(String resultCode) {
        if (resultCodePrefix == null) {
            return resultCode;
        } else {
            return StringTools.concat('.', resultCodePrefix, resultCode);
        }
    }

    /** 设置结果返回码资源文件前缀 **/
    public void setResultCodePrefix(String resultCodePrefix) {
        this.resultCodePrefix = resultCodePrefix;
    }
}
